import type { ProxyOptions } from 'vite';
import process from 'node:process';
import { fileURLToPath, URL } from 'node:url';
import { getAppBaseName } from '@lingshu/integration-vue3/dist/baseName';
import { ViteLangMergePlugin } from '@lingshu/language-lib/node';
import mswMockPlugin from '@lingshu/vite-plugin-msw';
import sharePlugin from '@lingshu/vite-plugin-share';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import UnoCSS from 'unocss/vite';
import { defineConfig, loadEnv } from 'vite';
import svgLoader from 'vite-svg-loader';

const proxyList = [
  '/app-role-matrix',
  '/auth',
  '/app-qbee-message',
  '/di-web',
  '/insight',
  '/app-cisdigital-lingshu-audit',
  '/api/lang',
];
const isProduction = process.env.NODE_ENV === 'production';
const base = getAppBaseName('rbac');

export default defineConfig((configEnv) => {
  const apiBase = loadEnv(configEnv.mode, process.cwd()).VITE_API_BASE;
  const proxyMap: Record<string, string | ProxyOptions> = proxyList.reduce((acc, cur) => {
    acc[cur] = {
      target: 'http://dev-minmetals.cisdigital.cn',
      changeOrigin: true,
      ws: false,
    };
    return acc;
  }, {} as Record<string, string | ProxyOptions>);

  return {
    base,
    plugins: [
      vue(),
      vueJsx(),
      UnoCSS(),
      mswMockPlugin(configEnv.mode),
      sharePlugin(
        configEnv,
        {
          sharedCss: [
            {
              name: 'element-plus-cisdi',
              paths: [
                'dist/index.css',
                'theme-chalk/cisdi-css-vars.css',
                'theme-chalk/dark/css-vars.css',
                'theme-chalk/dark/cisdi-css-vars.css',
              ],
            },
            {
              name: '@lingshu/theme-palette',
              paths: [
                'index.css',
              ],
            },
          ],
        },
      ),
      ViteLangMergePlugin(configEnv),
      svgLoader(),
    ],
    esbuild: {
      drop: isProduction ? ['console', 'debugger'] : [],
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@iconify/json': 'node_modules/@iconify/json/dist/json',
        '__CONDITIONAL_IMPORT__': isProduction ? `./BuildImport.ts` : './DevImport.ts',
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `
            @use '@/styles/variables.scss' as *;
            @use '@/styles/mixins.scss' as *;
          `,
        },
      },
    },
    build: {
      sourcemap: false,
    },
    server: {
      open: true,
      proxy: {
        ...proxyMap,
        '/biz-gateway': {
          target: apiBase,
          changeOrigin: true,
          ws: false,
        },
      },
    },
  };
});
